import moment from 'moment';
import { appId, templateIds } from '@/config/env';

export default {
    methods: {
        toBuy(item, type, index) {
            if (item.goodSource == 1) {
                this.statisEvent(type, index);
                this.$root.openRP(() => {
                    const next = () => {
                        const { jljLink, hasBuy, id, allowanceMoney } = item;

                        if (hasBuy) {
                            this.toJD(jljLink);
                        } else {
                            uni.showLoading({
                                title: '加载中'
                            });

                            this.$service.wxjlj
                                .getUserRecord(id)
                                .then(res => {
                                    if (res.jljLink) {
                                        uni.hideLoading();

                                        item.hasBuy = 1;
                                        item.jljLink = res.jljLink;

                                        this.toJD(res.jljLink);
                                    } else {
                                        this.$service.jingdong
                                            .createShortUrlForActivity({
                                                mdId: id
                                            })
                                            .then(async res => {
                                                uni.hideLoading();

                                                item.hasBuy = 1;
                                                item.jljLink = res;

                                                this.toJD(res);
                                                this.$store.commit('BUY', allowanceMoney);
                                            })
                                            .catch(err => {
                                                uni.hideLoading();
                                                uni.showToast({
                                                    title: err,
                                                    icon: 'none'
                                                });

                                                if (err.includes('已抢完')) {
                                                    item.receiveStatus = 1;
                                                    item.surplus = 0;
                                                }

                                                if (err.includes('您已抢购该商品')) {
                                                    item.hasBuy = 1;
                                                }

                                                this.$emit('change', item);
                                            });
                                    }
                                })
                                .catch(err => {
                                    uni.hideLoading();
                                    uni.showToast({
                                        title: err,
                                        icon: 'none'
                                    });
                                });
                        }
                    };

                    const isGrab = uni.getStorageSync('subscribe-message__grab-btn');

                    if (isGrab) {
                        next();
                    } else {
                        this.subscribeMessage().then(() => {
                            uni.setStorageSync('subscribe-message__grab-btn', true);
                            next();
                        });
                    }
                });
            } else {
                this.$root.openRP(() => {
                    const nextPdd = () => {
                        let info = uni.getStorageSync('userInfo');
                        let channelId = uni.getStorageSync('channelId');
                        let pagePath = `package_a/welfare_coupon/welfare_coupon?goods_id=${
                            item.gid
                        }&pid=10551839_182005128&customParameters=${JSON.stringify({
                            app: info.app,
                            userId: info.id,
                            channelId
                        })}&authDuoId=10551839`;
                        console.log(pagePath);
                        uni.navigateToMiniProgram({
                            appId: 'wx32540bd863b27570',
                            path: pagePath
                        });
                    };

                    const isGrab = uni.getStorageSync('subscribe-message__grab-btn');
                    if (isGrab) {
                        nextPdd();
                    } else {
                        this.subscribeMessage().then(() => {
                            uni.setStorageSync('subscribe-message__grab-btn', true);
                            nextPdd();
                        });
                    }
                });
            }
        },

        toJD(url) {
            this.$sdk.api('jdtrade', {
                url
            });
        },

        subscribeMessage() {
            return new Promise(resolve => {
                const old = uni.getStorageSync('subscribe-date');

                if (
                    !old ||
                    moment(old).isBefore(
                        moment()
                            .hour(0)
                            .minute(0)
                            .second(0)
                    )
                ) {
                    uni.setStorageSync('subscribe-date', moment().format('YYYY-MM-DD HH:mm:ss'));

                    const req = data => {
                        templateIds.forEach(id => {
                            this.$service.wechatApplet
                                .saveTemplateStatus({
                                    appId,
                                    openId: this.userInfo.openId,
                                    templateId: id,
                                    status: data[id]
                                })
                                .catch(err => {
                                    uni.showToast({
                                        title: err,
                                        icon: 'none'
                                    });
                                });
                        });
                    };

                    wx.requestSubscribeMessage({
                        tmplIds: templateIds,
                        success(res) {
                            req(res);
                            resolve();
                        },
                        fail(err) {
                            console.error(err);
                            req(err);
                            resolve();
                        }
                    });
                } else {
                    resolve();
                }
            });
        },

        // 统计事件
        statisEvent(type, index) {
            switch (type) {
                case 'tttj':
                    uni.reportAnalytics('click_tttj', {});
                    break;
                case 'bdhw':
                    uni.reportAnalytics('click_bdhhgoods', {});
                    break;
                case 'bdny':
                    let i1 = index + 1;

                    if (i1 <= 3) {
                        let name = 'click_bd_goods' + i1;
                        uni.reportAnalytics(name, {});
                    }
                    break;
                case 'xsyh':
                    let i2 = index + 1;
                    if (i2 <= 5) {
                        let name = 'click_xsyhgoods' + i2;
                        uni.reportAnalytics(name, {});
                    }
                    break;
                case '127':
                    if (index <= 3) {
                        let name = 'click_clothine_goods' + index;
                        uni.reportAnalytics(name, {});
                    }
                    break;
                case '128':
                    if (index <= 3) {
                        let name = 'click_babytoys_goods' + index;
                        uni.reportAnalytics(name, {});
                    }
                    break;
                case '129':
                    if (index <= 3) {
                        let name = 'click_makeups_goods' + index;
                        uni.reportAnalytics(name, {});
                    }
                    break;
                case '130':
                    if (index <= 3) {
                        let name = 'click_homelife_goods' + index;
                        uni.reportAnalytics(name, {});
                    }
                    break;
                case '131':
                    if (index <= 3) {
                        let name = 'click_luggage_goods' + index;
                        uni.reportAnalytics(name, {});
                    }
                    break;
                case '132':
                    if (index <= 3) {
                        let name = 'click_gourmet_goods' + index;
                        uni.reportAnalytics(name, {});
                    }
                    break;
                case '133':
                    if (index <= 3) {
                        let name = 'click_style_goods' + index;
                        uni.reportAnalytics(name, {});
                    }
                    break;
                case '134':
                    if (index <= 3) {
                        let name = 'click_digital_goods' + index;
                        uni.reportAnalytics(name, {});
                    }
                    break;
            }
        }
    }
};
